package crmdna.mail;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.microtripit.mandrillapp.lutung.MandrillApi;
import com.microtripit.mandrillapp.lutung.model.MandrillApiError;
import com.microtripit.mandrillapp.lutung.view.MandrillMessage;
import com.microtripit.mandrillapp.lutung.view.MandrillMessage.MergeVar;
import com.microtripit.mandrillapp.lutung.view.MandrillMessage.MergeVarBucket;
import com.microtripit.mandrillapp.lutung.view.MandrillMessage.Recipient;
import com.microtripit.mandrillapp.lutung.view.MandrillMessageStatus;

public class MailMessage {
	
	public static class MailContact {
		public String firstName;
		public String lastName;
		public String emailAddress;
		
		public MailContact(String firstName, String lastName, String emailAddress) {
			this.firstName = firstName;
			this.lastName = lastName;
			this.emailAddress = emailAddress;
		}
	}
	
	public static void sendMail(List<MailContact> contacts, String vendorName, String subject, String htmlContent) {
		
		MandrillMessage message = new MandrillMessage();
		message.setSubject(subject);
		message.setHtml(htmlContent);
		message.setAutoText(true);		
		message.setTrackClicks(true);
		message.setTrackOpens(true);
		
		
		MailVendor vendor = new MailVendor(vendorName);
		message.setFromEmail(vendor.getFromEmail());
		message.setFromName(vendor.getFromName());
		
		ArrayList<Recipient> rcps = new ArrayList<Recipient>();
		ArrayList<MergeVarBucket> mvbs = new ArrayList<MergeVarBucket>();
		
		for (MailContact contact : contacts) {
			Recipient rcp = new Recipient();
			rcp.setEmail(contact.emailAddress);
			rcps.add(rcp);
			
			MergeVar[] vars = new MergeVar[1];
			vars[0] = new MergeVar("FIRST_NAME", contact.firstName);

			MergeVarBucket mvb = new MergeVarBucket();
			mvb.setRcpt(contact.emailAddress);
			mvb.setVars(vars);
			mvbs.add(mvb);
		}
		
		message.setMergeVars(mvbs);
		message.setMerge(true);
		message.setTo(rcps);
		
		try {
			MandrillApi mandrillApi = new MandrillApi(vendor.getApiKey());
			mandrillApi.messages().send(message, false); //MandrillMessageStatus[] messageStatusReports = 
		}
		catch (MandrillApiError ex) {
			System.out.println(ex.toString());
		}
		catch (IOException ex) {
			System.out.println(ex.toString());
		}
	}
	
}
